﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using CommonLib;
using NetService;

namespace NwProvider
{
    internal static class NwArticleProvider
    {
        public static List<string> GetArticles(int count)
        {
            var res = new List<string>();

            int i = 0;

            do
            {
                var url = string.Format(NEWSWEEK_URL, i * 10);

                var text = PageService.GetPage(url);

                var pages = HtmlPagesParser.GetPages(text);

                foreach (var resIter in pages)
                {
                    if (!res.Contains(resIter.Value))
                        res.Add(resIter.Value);
                }

                Thread.Sleep(1000);

                i++;
            } while (count > res.Count);

            return res;
        }

        public static WordStatArticle GetArticle(string url)
        {
            try
            {
                var text = PageService.GetPage(url, Encoding.Unicode);

                if (string.IsNullOrEmpty(text))
                    return null;

                return GetArticleData(url, text);
            }
            catch (Exception)
            {
            }

            return null;
        }

        private static WordStatArticle GetArticleData(string url, string text)
        {
            try
            {
                var article = new WordStatArticle { Author = HtmlParser.GetAuthor(text) };

                if (string.IsNullOrEmpty(article.Author))
                    return null;

                article.Date = HtmlParser.GetDate(text);

                article.Url = url;

                var title = HtmlParser.GetTitle(text);

                if (string.IsNullOrEmpty(title))
                    return null;


                article.Text = HtmlParser.GetArticle(text).Trim();

                if (string.IsNullOrEmpty(article.Text))
                    return null;

                article.Words = WordParser.GetWords(article.Text);

                if (article.Words.Count == 0)
                    return null;

                article.Source = "NewsWeek";

                return article;

            }
            catch (Exception e)
            {
            }

            return null;
        }

        private const string NEWSWEEK_URL = @"http://www.newsweek.com/tag/politics.html?start={0}";
    }
}
